package com.bruceliu.service.impl;

import com.bruceliu.bean.Cart;
import com.bruceliu.bean.Item;
import com.bruceliu.bean.Order;
import com.bruceliu.mapper.OrderMapper;
import com.bruceliu.service.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @BelongsProject: RestaurantSystem
 * @BelongsPackage: com.bruceliu.service.impl
 * @Author: bruceliu
 * @QQ:1241488705
 * @CreateTime: 2020-03-01 23:59
 * @Description: TODO
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    OrderMapper orderMapper;

    @Resource
    CartService cartService;

    @Resource
    DeskService deskService;

    @Resource
    FoodService foodService;

    @Resource
    ItemService itemService;

    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
    @Override
    public int addOrder(int desk_id) {
        List<Cart> carts = cartService.getCarts(desk_id);
        double sum=0.0;
        for (Cart cart : carts) {
            sum=sum+cart.getTotal();
        }
        Order order=new Order();
        order.setDesk(deskService.getById(desk_id));
        order.setState(0);
        order.setTotalfee(sum);
        //新增订单表(返回订单主键)
        int count = orderMapper.addOrder(order);
        System.out.println("新增Order表成功之后的主键是："+order.getOid());

        int index=0;
        for (Cart cart : carts) {
            Item item=new Item();
            item.setFood(cart.getFood());
            item.setOrder(order);
            item.setNum(cart.getNum());
            itemService.addItem(item);
            index++;
        }
        //情况购物车
        cartService.deleteCart(desk_id);
        return count+index;
    }

    @Override
    public Order getByDeskId(int desk_id) {
        return orderMapper.getByDeskId(desk_id);
    }

    @Override
    public List<Order> getOrders() {
        return orderMapper.getOrders();
    }
}
